package com.bomb.voice.feature.operationAccount;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.widget.Toast;

import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.bomb.voice.MyApp;
import com.bomb.voice.R;
import com.bomb.voice.backNet.AddAccountBean;
import com.bomb.voice.bean.MyUser;
import com.bomb.voice.net.HttpSubscriber;
import com.bomb.voice.net.request.VoiceLoader;
import com.bomb.voice.utils.AccountConfig;
import com.vipheyue.fastlib.dialog.FastProgressDialog;
import com.vipheyue.fastlib.utils.Flog;
import com.vipheyue.fastlib.utils.SharePreferencesUtil;

import cn.bmob.v3.BmobInstallation;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;


public class LoginActivity extends AppCompatActivity {
    String installationId = BmobInstallation.getCurrentInstallation().getInstallationId();
    String fyAccountId = SharePreferencesUtil.getSpString("fyAccountId", "", MyApp.get());
    String fyAccountPwd = SharePreferencesUtil.getSpString("fyAccountPwd", "", MyApp.get());
    private FastProgressDialog fastProgressDialog;//避免创建重复View，先创建View，然后需要的时候show出来，推荐这个做法
    private AlertView mAlertView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        fastProgressDialog = new FastProgressDialog(this, "登录中");

        initIntent();
//        dealWithError("");
    }

    private void initIntent() {
        fastProgressDialog.show();
        if (TextUtils.isEmpty(fyAccountId)) {
            createFyAccount();
        } else {
            loginBmob();
        }
    }

    private void loginBmob() {
        MyUser bu2 = new MyUser();
        bu2.setUsername(installationId);    //默认以设备的installationId为用户名
        bu2.setPassword(AccountConfig.defaultAccountPwd);//密码也是默认
        bu2.login(listener);
    }


    private void registerBmobAccount(String voiceID, String voicePwd) {
        MyUser bu = new MyUser(voiceID, voicePwd, AccountConfig.defaultRemainCallTimes);
        bu.setUsername(installationId);    //默认以设备的installationId为用户名
        bu.setPassword(AccountConfig.defaultAccountPwd);//密码也是默认
//注意：不能用save方法进行注册
        bu.signUp(listener);
    }

    SaveListener<MyUser> listener = new SaveListener<MyUser>() {
        @Override
        public void done(MyUser myUser, BmobException e) {
            if (e == null) {
                goFaceTimeActivity(); //已登录状态
            } else {
                dealWithError(e.getLocalizedMessage());
            }
        }
    };

    private void createFyAccount() {
        Flog.e(installationId);
        VoiceLoader voiceBackLoader = new VoiceLoader();
        voiceBackLoader.addAccount(installationId).subscribe(new HttpSubscriber<AddAccountBean>() {
            @Override
            public void onNext(AddAccountBean addAccountBean) {
                //得到 飞语账户和名字 通过 resultMsg 判断 需要注册还是登录
                AddAccountBean.ResultBean result = addAccountBean.getResult();

                String fyAccountId = result.getFyAccountId();
                String fyAccountPwd = result.getFyAccountPwd();
                SharePreferencesUtil.putSpString("fyAccountId", fyAccountId, LoginActivity.this);
                SharePreferencesUtil.putSpString("fyAccountPwd", fyAccountPwd, LoginActivity.this);

                registerBmobAccount(fyAccountId, fyAccountPwd);
            }
        });
    }

    private void dealWithError(String localizedMessage) {
        fastProgressDialog.dismiss();
        mAlertView = new AlertView("发生错误", "登录失败--> 点击重试\r\n 详细日志:" + localizedMessage, null, new String[]{"重试"}, null, this, AlertView.Style.Alert, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                initIntent();
            }
        }).setCancelable(true);
        mAlertView.show();
        Toast.makeText(this, localizedMessage, Toast.LENGTH_SHORT).show();
    }

    private void goFaceTimeActivity() {
        fastProgressDialog.dismiss();

        startActivity(new Intent(this, FaceTimeActivity.class));
        finish();
    }


}
